package com.webserver.core;

import com.webserver.controller.UserController;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

/**
 * 用于处理请求
 */
public class DispatcherServlet {
    private static File root;
    private static File staticDir;
    static {
        try {
            root = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(root,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }

    public void service(HttpServletResponse response, HttpServletRequest request){
        String path = request.getRequestURI();//path: /myweb/index.html

//        System.out.println(path+"=========================================");
        if ("/myweb/reg".equals(path)){
            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!开始处理注册");
            UserController controller = new UserController();
            controller.reg(response,request);
        }else if ("/myweb/login".equals(path)){
            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!开始处理登录");
            UserController controller = new UserController();
            controller.login(response,request);
        }else {
            File file = new File(staticDir,path);
//            System.out.println("页面是否存在: "+file.exists());
            if (file.isFile()){
                response.setContentFile(file);

            }else {
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File(staticDir,"root/404.html");
                response.setContentFile(file);
            }
        }
        //测试添加一个额外的响应头
//        response.addHeader("server","WebServer");
    }




}
